import requests
import json
import pandas as pd
import uuid
import os
import sys
import time
import argparse
from typing import Dict, List, Any

# 添加项目根目录到系统路径
sys.path.append(
    os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
)

# 导入net模块的配置
from net.config import current_config

# from common.train_dict import classify_problem, get_dict_name  # 导入字典查询函数
# from common.person_dict import process_persons_list  # 导入人员字典处理模块
# from save.net_save_nofyrs import save_to_txt, get_last_position, save_position, POSITION_PATH  # 导入保存相关的函数

# 配置命令行参数
parser = argparse.ArgumentParser(description="网络举报件处理程序")
parser.add_argument(
    "--excel_file", type=str, default="net.xlsx", help="Excel文件路径"
)
args = parser.parse_args()

# 设置请求超时时间（秒）
REQUEST_TIMEOUT = 300

# 设置Excel文件名
EXCEL_FILE = args.excel_file

# 根据环境配置构建API地址
API_URL = f"http://{current_config['host']}:{current_config['port']}/api/getNetLetters"


def process_person_info(name: str, **kwargs) -> Dict[str, str]:
    """处理人员信息"""
    return {
        "bh": str(uuid.uuid4()).replace("-", ""),
        "mc": name.strip(),
        **{k: v.strip() for k, v in kwargs.items() if v},
    }


def process_persons_list(names: str, **kwargs) -> List[Dict[str, str]]:
    """处理人员列表"""
    if not pd.isna(names):
        name_list = str(names).split(";")
        return [
            process_person_info(name, **kwargs) for name in name_list if name.strip()
        ]
    return []


def prepare_request_data(row: pd.Series) -> Dict[str, Any]:
    """准备请求数据"""
    # 处理反映人信息
    fyrs = process_persons_list(row["反映人姓名"])

    # 处理被反映人信息
    bfyrs = []
    if pd.notna(row["被反映人姓名"]):
        bfyr_names = str(row["被反映人姓名"]).split(";")
        bfyr_zw = (
            str(row["被反映人职务"]).split(";")
            if pd.notna(row["被反映人职务"])
            else [""] * len(bfyr_names)
        )
        bfyr_zj = (
            str(row["被反映人职级"]).split(";")
            if pd.notna(row["被反映人职级"])
            else [""] * len(bfyr_names)
        )
        bfyr_dwhdz = (
            str(row["被反映人单位或地址"]).split(";")
            if pd.notna(row["被反映人单位或地址"])
            else [""] * len(bfyr_names)
        )

        # 确保所有列表长度一致
        max_len = max(len(bfyr_names), len(bfyr_zw), len(bfyr_zj), len(bfyr_dwhdz))
        bfyr_zw.extend([""] * (max_len - len(bfyr_zw)))
        bfyr_zj.extend([""] * (max_len - len(bfyr_zj)))
        bfyr_dwhdz.extend([""] * (max_len - len(bfyr_dwhdz)))

        for i, name in enumerate(bfyr_names):
            if name.strip():
                bfyrs.append(
                    process_person_info(
                        name, zw=bfyr_zw[i], zj=bfyr_zj[i], dwhdz=bfyr_dwhdz[i]
                    )
                )

    # 处理初次件信息
    cfj = []
    if pd.notna(row["初次件"]):
        cfj.append(
            {
                "bh": str(uuid.uuid4()).replace("-", ""),
                "wtxx": {"yjms": str(row["初次件"])},
            }
        )

    # 清理和验证caseIntruction字段
    case_instruction = ""
    if pd.notna(row["原件描述"]):
        case_instruction = str(row["原件描述"]).strip()
        # 移除可能的重复内容
        if case_instruction:
            # 如果内容过长，可能包含重复，尝试清理
            lines = case_instruction.split("\n")
            cleaned_lines = []
            seen_lines = set()
            for line in lines:
                line = line.strip()
                if line and line not in seen_lines:
                    cleaned_lines.append(line)
                    seen_lines.add(line)
            case_instruction = "\n".join(cleaned_lines)

    return {
        "bh": str(row["信访举报件编号"]),
        "caseIntruction": case_instruction,
        ##"fyrs": fyrs,
        "bfyrs": bfyrs,
        "cfj": cfj,
        "ysbh": (
            str(row["原始编号"])
            if "原始编号" in row and not pd.isna(row["原始编号"])
            else ""
        ),
    }


def send_request(data: Dict[str, Any], index: int) -> bool:
    """发送请求并处理响应"""
    print(f"\n处理第 {index + 1} 条数据:")

    # 验证请求数据的完整性
    if not data.get("bh"):
        print("错误：缺少信访举报件编号")
        return False

    if not data.get("caseIntruction"):
        print("错误：缺少原件描述")
        return False

    # 检查caseIntruction长度，如果过长可能有问题
    if len(data["caseIntruction"]) > 10000:  # 设置合理的长度限制
        print("警告：原件描述内容过长，可能存在重复")
        # 截取前5000个字符
        data["caseIntruction"] = data["caseIntruction"][:5000] + "..."

    print("发送请求数据:")
    print(json.dumps(data, ensure_ascii=False, indent=2))

    try:
        response = requests.post(API_URL, json=data, timeout=REQUEST_TIMEOUT)

        # 检查响应状态码
        response.raise_for_status()

        # 解析JSON响应
        result = response.json()
        print("\n响应状态码:", response.status_code)
        print("响应内容:")
        print(json.dumps(result, ensure_ascii=False, indent=2))

        return result.get("success") == "true"

    except requests.exceptions.Timeout:
        print(f"请求超时（{REQUEST_TIMEOUT}秒），跳过当前数据")
        return False
    except requests.exceptions.RequestException as e:
        print(f"请求错误: {str(e)}")
        # 如果是500错误，打印更多调试信息
        if "500" in str(e):
            print("服务器内部错误，可能是请求数据格式问题")
            print("请检查以下字段：")
            print(f"- bh: {data.get('bh', 'N/A')}")
            print(f"- caseIntruction长度: {len(data.get('caseIntruction', ''))}")
            print(f"- bfyrs数量: {len(data.get('bfyrs', []))}")
        return False
    except json.JSONDecodeError as e:
        print("JSON解析错误:", str(e))
        print("原始响应内容:", response.text)
        return False


def main():
    """主函数"""
    try:
        # 读取Excel文件
        df = pd.read_excel(EXCEL_FILE, sheet_name="Sheet1")

        # 数据预处理：清理空值和格式问题
        print(f"正在处理Excel文件: {EXCEL_FILE}")
        print(f"读取到 {len(df)} 条数据")

        # 检查必要的列是否存在
        required_columns = ["信访举报件编号", "原件描述"]
        missing_columns = [col for col in required_columns if col not in df.columns]
        if missing_columns:
            print(f"错误：Excel文件缺少必要的列: {missing_columns}")
            return

        # 清理数据
        df = df.dropna(subset=["信访举报件编号", "原件描述"])  # 删除关键字段为空的行
        print(f"清理后剩余 {len(df)} 条有效数据")

        # 遍历每一行数据
        for index, row in df.iterrows():
            print(f"\n{'='*50}")
            print(f"开始处理第 {index + 1} 条数据")
            print(f"信访举报件编号: {row['信访举报件编号']}")

            # 准备请求数据
            request_data = prepare_request_data(row)

            # 发送请求
            success = send_request(request_data, index)

            # 如果请求失败，等待一段时间后继续
            if not success:
                print("请求失败，等待5秒后继续...")
                time.sleep(5)  # 失败后等待5秒再继续
            else:
                print("请求成功！")

    except FileNotFoundError:
        print(f"错误：找不到{EXCEL_FILE}文件")
    except pd.errors.EmptyDataError:
        print("错误：Excel文件为空")
    except Exception as e:
        print("其他错误:", str(e))
        import traceback

        traceback.print_exc()


if __name__ == "__main__":
    main()
